<template>
  <div class="app-container">
    <el-form ref="dataForm" :model="dataForm" status-icon :rules="rules"
             label-position="left" label-width="110px" style="width: 600px; margin-left:50px;">
      <el-form-item :label='$t("会员名称")'  prop="name">
        <el-input v-model="dataForm.name" maxlength="64" clearable/>
      </el-form-item>
      <el-form-item :label='$t("等级有效期")' prop="expiredDays" style="line-height: 46px;">
        <el-radio-group v-model="expiredDays" @change="ChangeRadio(expiredDays)">
          <el-radio :label="0">{{$t('永久有效')}}</el-radio>
          <div class='heig'></div>
          <el-radio :label="1">
            {{$t('有效期')}}
            <el-input v-model="dataForm.expiredDays" @focus="InputFocus(expiredDays=1)" clearable/>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label='$t("升级条件")' prop="autoSub" style="line-height: 46px;">
        <el-radio-group v-model="pgradeStatus" @change="RadioChange(pgradeStatus)">
          <el-radio :label="0">{{$t('无')}}</el-radio>
          <div class='heig'></div>
          <el-radio :label="1">
            {{$t('有效期内累计消费')}}
            <el-input v-model="dataForm.upgradeMoney" @focus="InputFocus(pgradeStatus=1,dataForm.upgradePoint='')"
                      clearable/>
          </el-radio>
          <div class='heig'></div>
          <el-radio :label="2">
            {{$t('有效期内累计积分')}}
            <el-input v-model="dataForm.upgradePoint" @focus="InputFocus(pgradeStatus=2,dataForm.upgradeMoney='')"
                      clearable/>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label='$t("保级规则")' prop="saveLevelMoney">
        {{$t('有效期内累计消费')}}
        <el-input style="width:100px" v-model="dataForm.saveLevelMoney" clearable/>
      </el-form-item>
      <el-form-item :label='$t("上一级")' prop="pid">
        <el-select v-if="type!=2" v-model="dataForm.pid" :placeholder='$t("无")' clearable>
            <span v-for="(item)  in listStatus" v-bind:key="item.id">
             <el-option :label="item.name" :value="item.id"></el-option>
            </span>
        </el-select>
        <div v-else>
            <span>
              {{dataForm.pname}}
            </span>
        </div>
      </el-form-item>
      <el-form-item :label='$t("积分获取比例")' prop="pointRatio">
        {{$t('消费')}} 1 {{$t('元')}}  =
        <el-input style="width:100px" v-model="dataForm.pointRatio" clearable/>
        {{$t('积分')}}
      </el-form-item>
      <div class='TipsTitle'>{{$t('专享福利')}}</div>
      <div class='TopAdd'>
        <div></div>
        <el-button class="filter-item" type="warning" plain1 icon="el-icon-circle-plus" @click="handleAttributeShow">{{$t('Add')}}
        </el-button>
      </div>
      <el-table border :data="this.list">
        <el-table-column :label='$t("名称")' align="center" prop="name"></el-table-column>
        <el-table-column :label='$t("数量")' prop="total" align="center"></el-table-column>
        <el-table-column align="center" :label='$t("类型")' prop="discountType">
          <template slot-scope="scope">
            <el-tag>
             {{ $t(scope.row.discountType == 1 ? '订阅' : '优惠券') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('Operate')" width="80" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleDelete(scope.$index,scope.row)">{{$t('Delete')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :visible.sync="attributeVisiable" title="添加/设置福利">
        <el-form ref="attributeForm" :model="attributeForm" status-icon label-position="left" label-width="100px"
                 style=" margin-left:50px;">
          <el-form-item :label='$t("选择类型")' prop="discountType">
            <el-radio-group v-model="attributeForm.discountType" @change="RadioChanges(attributeForm.discountType)">

              <el-radio v-model="attributeForm.discountType" :label="1">{{$t('订阅')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label='$t("优惠券")' prop="attribute" v-if="attributeForm.discountType==0">
            <el-select v-model="attributeForm.pid" :placeholder='$t("无")'>
                <span v-for="(item)  in this.listCoupon" v-bind:key="item.id">
                  <el-option :label="item.name" :value="item.id"></el-option>
                </span>
            </el-select>
          </el-form-item>
          <el-form-item :label='$t("订阅")' prop="attributeForm.subscribeId" v-if="attributeForm.discountType==1">
            <el-select v-model="attributeForm.subscribeId" :placeholder='$t("无")'
                       @change="SelectChange(attributeForm.subscribeId)">
                <span v-for="(item)  in this.listLumiereSubscribe" v-bind:key="item.id">
                  <el-option :label="item.name" :value="item.id"></el-option>
                </span>
            </el-select>
          </el-form-item>
          <el-form-item :label='$t("礼物卡")' prop="attribute" v-if="attributeForm.discountType==2">
            <el-select v-model="attributeForm.gid" :placeholder='$t("无")'>
                <span v-for="(item)  in this.listGiftCard" v-bind:key="item.id">
                  <el-option :label="item.name" :value="item.id"></el-option>
                </span>
            </el-select>
          </el-form-item>
          <el-form-item :label='$t("发放周期")' prop="frequency" v-if="attributeForm.discountType==0">
            <el-radio v-model="attributeForm.frequency" :label="1">{{$t('每天')}}</el-radio>
            <el-radio v-model="attributeForm.frequency" :label="2">{{$t('每周')}}</el-radio>
            <div></div>
            <el-radio v-model="attributeForm.frequency" :label="3">{{$t('每月')}}</el-radio>
            <el-radio v-model="attributeForm.frequency" :label="4">{{$t('每年')}}</el-radio>
          </el-form-item>

          <el-form-item :label='$t("订阅方式")' prop="frequency" v-if="attributeForm.discountType==1">
                 <span v-for="item in rule" v-bind:key="item.id" prop="rules">
                   <el-radio v-model="attributeForm.rules" :label="item.id">{{formateSubscribeRule(item)}}</el-radio><div></div>
                 </span>
          </el-form-item>
          <el-form-item :label='$t("数量")' prop="total" v-if="attributeForm.discountType==0">
            <el-input :placeholder='$t("请填写数量")' v-model="attributeForm.total" style="width:202px"/>
          </el-form-item>
        </el-form>
        <el-button style="width:150px" type="primary" plain1 round icon="el-icon-success" @click="handleAttributeAdd">{{$t('Confirm')}}</el-button>
      </el-dialog>

    </el-form>
    <div class="op-container">
      <el-button @click="handleBack" style="margin-right: 480px">{{$t('返回')}}</el-button>
      <el-button v-if="dialogStatus=='create'" type="primary" @click="createData"
                 v-permission="['GET /admin/p/member_level_add']">{{$t('Confirm')}}
      </el-button>
      <el-button v-if="this.status== false" type="primary" @click="updateData"
                 v-permission="['GET /admin/p/member_level_edit']">{{$t('Confirm')}}
      </el-button>
    </div>
  </div>
</template>

<script>
  import { getToken } from '../../utils/auth'

  import { listCoupon,listInMember } from '../../api/coupon'
  import { listGiftCard } from '../../api/gift'
  import { listLumiereSubscribe } from '../../api/lumiereSubscribe'

  import {
    listGoodsOnSale,
    getSpecificationByGoods
  } from '../../api/lumiereSubscribe'
  import { queryMemberNoChildren, levelMemberAdd, levelMemberDetail, levelMemberUpdata } from '@/api/user'

  export default {
    name: 'addedUser',
    data() {
      return {
        attributeVisiable: false,
        id: '',
        status: undefined,
        type: '',
        attributeForm: {
          frequency: 1,
          discountType: 0,
          total: ''
        },
        couponDtos: [],
        giftCard:[],
        subscribeVos: [],
        giftCardVos: [],
        //  subscribeRuleIds:[],//订阅规则Id数组
        //  giftCardIds:[],//礼物卡Id数组
        rule: [],
        dialogFormVisible: false,
        dialogStatus: '',
        pgradeStatus: 0,
        expiredDays: 0,
        rules: {
          name: [{ required: true, message: this.$t('会员名称必填'), trigger: 'blur' }]
        },
        dataForm: {
          name: undefined,
          expiredDays: '',
          upgradeMoney: '',
          upgradePoint: '',
          saveLevelMoney: '',
          saveLevelPoint: '',
          pointRatio: '',
          pid: '',
          couponDtos: '',

          subscribeRuleIds: '',
          giftCardIds: ''
        },
        listStatus: [],
        list: [],
        listCoupon: [],
        listGiftCard: [],
        coupon: [],
        listLumiereSubscribe: []

      }
    },
    async created() {
      if (this.$route.query.status == 2) {
        this.status = true
      } else {
        this.status = false
      }

      await this.queryMemberNoChildren()
      await this.GetListCoupon()
      await this.GetListLumiereSubscribe()
      await this.listCategory()
      await this.getListGiftCard()
      if (this.$route.query.type == 2) {
        await this.getGoods(this.$route.query.id)
        this.type = this.$route.query.type
        this.id = this.$route.query.id
      }

    },
    methods: {
      ChangeRadio(row) {
        if (row == 0) {
          this.dataForm.expiredDays = ''
        }

      },
      InputFocus() {
      },
      RadioChange(row) {
        if (row == 0) {
          this.dataForm.upgradePoint = ''
          this.dataForm.upgradeMoney = ''
        } else if (row == 1) {
          this.dataForm.upgradePoint = ''
        } else if (row == 2) {
          this.dataForm.upgradeMoney = ''
        }
      },

      // 下一级查询
      queryMemberNoChildren() {
        return queryMemberNoChildren().then(res => {
          this.listStatus = res.data.data.list
          // console.log('下一级查询',this.listSturnts)
        })
      },

      GetListCoupon() {
        var data = {
          type: 1, sort: 'add_time', order: 'desc', page: 1,
          limit: 9999,isExpired: true
        }
        return listInMember(data).then(res => {
          this.listCoupon = res.data.data.list
          this.coupon = res.data.data.list

        })
      },
      GetListLumiereSubscribe() {
        var data = {
          status: 1, sort: 'add_time', order: 'desc', page: 1,
          limit: 9999
        }
        return listLumiereSubscribe(data).then(res => {
          this.listLumiereSubscribe = res.data.data.list

        })
      },

      getGoods(id) {
        levelMemberDetail({ 'memberId': id }).then(response => {
          this.dataForm = response.data.data
          this.expiredDays = this.dataForm.expiredDays == 0 ? 0 : 1
          this.dataForm.expiredDays = this.dataForm.expiredDays == 0 ? '' : this.dataForm.expiredDays
          this.pgradeStatus = this.dataForm.upgradeMoney != undefined ? 1 : this.dataForm.upgradePoint != undefined ? 2 : 0
          this.couponDtos = response.data.data.couponDtos
          this.subscribeVos = response.data.data.subscribeVos
          this.giftCardVos = response.data.data.giftCardVos
          var subscribeVos = response.data.data.subscribeVos
          var couponDtos = response.data.data.couponDtos
          var giftCardVos = response.data.data.giftCardVos


          for (var i = 0; i < couponDtos.length; i++) {
            couponDtos[i].total = couponDtos[i].number
            for (var j = 0; j < this.listCoupon.length; j++) {
              if (couponDtos[i].couponId == this.coupon[j].id) {
                couponDtos[i].name = this.listCoupon[j].name
              }
            }
          }
          for (var i = 0; i < subscribeVos.length; i++) {
            for (var j = 0; j < this.listLumiereSubscribe.length; j++) {
              if (subscribeVos[i].subscribeId == this.listLumiereSubscribe[j].id) {
                subscribeVos[i].name = this.listLumiereSubscribe[j].name
                subscribeVos[i].number = 1
                subscribeVos[i].total = 1
                subscribeVos[i].discountType = 1
              }
            }
          }

          for (var i = 0; i < giftCardVos.length; i++) {
            for (var j = 0; j < this.listGiftCard.length; j++) {
              if (giftCardVos[i].giftCardId == this.listGiftCard[j].id) {
                giftCardVos[i].number = 1
                giftCardVos[i].name = this.listGiftCard[j].name
                giftCardVos[i].total = 1
                giftCardVos[i].discountType = 2
              }
            }
          }


          // couponDtos.name = response.data.data.couponDtos.number
          // this.listCoupon
          this.list = [...couponDtos, ...subscribeVos,...giftCardVos]

        }).catch((response) => {
        })
      },
      handleBack() {
        this.$router.push({ path: '/user/MemberLevelSetting' })
      },
      createData() {
        // createSubscribe({"dto": this.dataForm}).then(response => {
        //   this.$router.push({path: '/subscribe/list'})
        // })
        // this.resetForm();
      },
      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (!valid) {
            return
          }
        })

        if (!this.dataForm.name) {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('请填写会员名称')
          })
          return
        } else if (this.expiredDays == 1 && !this.dataForm.expiredDays) {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('请填写有效时间')
          })
          return
        } else if (this.pgradeStatus == 1 && !this.dataForm.upgradeMoney) {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('升级条件金额')
          })
          return
        } else if (this.pgradeStatus == 2 && !this.dataForm.upgradePoint) {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('升级条件积分')
          })
          return
        } else if (!this.dataForm.saveLevelPoint && !this.dataForm.saveLevelMoney) {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('请填写保级条件')
          })
          return
        } else if (!this.dataForm.pointRatio) {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('请填写积分获取比例')
          })
          return
        }
        var data = {
          name: this.dataForm.name,
          id: this.id,
          expiredDays: this.expiredDays == 0 ? 0 : this.dataForm.expiredDays,//等级有效期
          upgradeMoney: this.pgradeStatus == 1 ? this.dataForm.upgradeMoney : undefined,//升级所需金额
          upgradePoint: this.pgradeStatus == 2 ? this.dataForm.upgradePoint : undefined,//升级所需金额
          saveLevelMoney: this.dataForm.saveLevelMoney,//保级所需金额
          saveLevelPoint: this.dataForm.saveLevelPoint,//保级所需积分
          pointRatio: this.dataForm.pointRatio,  //消费一元获取积分
          pid: this.dataForm.pid,//上级id
          status: this.dataForm.status,
          couponDtos: this.couponDtos.length <= 0 ? undefined : this.couponDtos,
          subscribeVos: this.subscribeVos.length <= 0 ? undefined : this.subscribeVos,
          giftCardVos: this.giftCardVos.length <=0 ? undefined : this.giftCardVos,
        }
        if (this.type == 2) {
          levelMemberUpdata(data).then(res => {
            this.$notify.success({
              title: this.$t('Success!'),
              message: res.data.data
            })
            this.$router.push({ path: '/user/MemberLevelSetting' })
          }).catch(res => {
            this.$notify.error({
              title: this.$t('Failed'),
              message: res.data.errmsg
            })
          })
        } else {
          levelMemberAdd(data).then(res => {
            this.$notify.success({
              title: this.$t('Success!'),
              message: res.data.data
            })
            this.$router.push({ path: '/user/MemberLevelSetting' })
          }).catch(res => {
            this.$notify.error({
              title: this.$t('Failed'),
              message: res.data.errmsg
            })
          })
        }

      },

      handleAttributeShow() {
        this.attributeForm = {
          frequency: 1,
          discountType: 0,
          pid: undefined,
          total: ''
        }
        this.rule = []
        this.listCoupon = this.coupon
        for (var i = 0; i < this.couponDtos.length; i++) {
          this.listCoupon = this.listCoupon.filter(item => item.id != this.couponDtos[i].couponId)
        }

        for (var i = 0; i < this.subscribeVos.length; i++) {
          this.listLumiereSubscribe = this.listLumiereSubscribe.filter(item => item.id != this.subscribeVos[i].subscribeId)
        }

        for (var i = 0; i < this.giftCardVos.length; i++) {
          this.listGiftCard = this.listGiftCard.filter(item => item.id != this.giftCardVos[i].giftCardId)
        }

        this.attributeVisiable = true
      },
      formateSubscribeRule(item) {
        let ruleStr = ''
        if (item.ruleType == 1) {
          ruleStr += this.$t('按周')
        } else if (item.ruleType == 2) {
          ruleStr += this.$t('按月')
        } else if (item.ruleType == 3) {
          ruleStr += this.$t('按年')
        }

        if (item.daysTimes != 0 && item.daysTimes != undefined) {
          ruleStr += '(每天配送' + item.daysTimes + '次)'
        }
        if (item.weekTimes != 0 && item.weekTimes != undefined) {
          ruleStr += '(每周配送' + item.weekTimes + '次)'
        }
        if (item.monthTimes != 0 && item.monthTimes != undefined) {
          ruleStr += '(每月配送' + item.monthTimes + '次)'
        }
        if (item.yearTimes != 0 && item.yearTimes != undefined) {
          ruleStr += '(每年配送' + item.yearTimes + '次)'
        }
        return ruleStr
      },
      SelectChange(row) {

        this.rule = (this.listLumiereSubscribe.filter(e => e.id == row)[0] || {}).rules
      },
      handleAttributeAdd() {
        if (this.attributeForm.discountType == 0) {
          if (this.attributeForm.pid == undefined) {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请填选择商品')
            })
            return
          }
          if (this.attributeForm.total == '' || this.attributeForm.total <= 0) {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请填写正确数量')
            })
            return
          }
          for (let i = 0; i < this.listCoupon.length; i++) {
            if (this.listCoupon[i].id == this.attributeForm.pid) {
              this.attributeForm.name = this.listCoupon[i].name
            }
          }
          var data = {
            couponId: this.attributeForm.pid,
            number: this.attributeForm.total,
            cycleType: this.attributeForm.frequency
          }
          this.couponDtos.push(data)
          this.list.push(this.attributeForm)
        } else if(this.attributeForm.discountType == 1) {
          if (this.attributeForm.subscribeId == undefined) {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请填选择商品')
            })
            return
          } else if (this.attributeForm.rules == undefined) {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请选择订阅规则')
            })
            return
          }
          for (let i = 0; i < this.listLumiereSubscribe.length; i++) {
            if (this.listLumiereSubscribe[i].id == this.attributeForm.subscribeId) {
              this.attributeForm.name = this.listLumiereSubscribe[i].name
              this.attributeForm.total = 1
              this.attributeForm.discountType = 1
            }
          }
          var data = {
            subscribeId: this.attributeForm.subscribeId,
            subscribeRuleIds: [this.attributeForm.rules],
            subscribeName: this.attributeForm.name
          }
          this.subscribeVos.push(data)
          this.list.push(this.attributeForm)
        }else{
          if(this.attributeForm.gid == null || this.attributeForm.gid == 'undefined'){
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请填选择礼物卡')
            })
            return
          }

          for (let i = 0; i < this.listGiftCard.length; i++) {
            if (this.listGiftCard[i].id == this.attributeForm.gid) {
              this.attributeForm.name = this.listGiftCard[i].name
              this.attributeForm.total = 1
              this.attributeForm.discountType = 2
            }
          }

          var data = {
            name: this.attributeForm.name,
            giftCardId: this.attributeForm.gid,
            number: 1
          }
          this.giftCardVos.push(data)
        }
        this.attributeVisiable = false
      },
      RadioChanges(row) {
        this.attributeForm = {
          frequency: 1,
          discountType: row,
          pid: undefined,
          total: ''
        }
      },
      handleDelete(data, row) {
        this.$confirm(this.$t('是否') + this.$t('删除该福利') + '?', this.$t('提示'), {
          confirmButtonText: this.$t('Confirm'),
          cancelButtonText: this.$t('Cancel'),
          type: 'warning'
        }).then(() => {
          this.list.splice(data, 1)
          if (row.subscribeId) {
            this.subscribeVos = this.subscribeVos.filter(item => item.subscribeId != row.subscribeId)
          } else {
            this.couponDtos = this.couponDtos.filter(item => item.couponId != row.couponId)
          }
        })
      },
      listCategory() {
       return  listGoodsOnSale().then(response => {
          this.goodsOnSale = response.data.data.list.map(goods => {
            return {
              label: goods.name,
              key: goods.id
            }
          })
        })
      },
      listSpecification() {
        this.specificationQuery = {
          goodsId: this.attributeForm.goodsId
        }
        getSpecificationByGoods(this.specificationQuery).then(response => {
          this.specificationList = response.data.data.list.map(specification => {
            return {
              label: specification.specification,
              key: specification.id,
              price: specification.price
            }
          })
        })
      },
      changeSpecification() {
        // this.attributeForm.number = 0
        for (let i = 0; i < this.specificationList.length; i++) {
          if (this.specificationList[i].key == this.attributeForm.specificationIds) {
            // //debugger
            if (this.attributeForm.number == undefined) {
              this.attributeForm.number = 0
            }
            this.attributeForm.basePrice = this.specificationList[i].price * this.attributeForm.number
          }
        }
      },
      getListGiftCard(){
        var data = {
          sort: 'add_time', order: 'desc', page: 1,
          limit: 9999,type:1,status:1,
        }
        return listGiftCard(data).then(res => {
          this.listGiftCard = res.data.data.list
          this.giftCard = res.data.data.list
        })
      },

    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    }
  }
</script>

<style scoped>
  .TipsTitle {
    line-height: 36px;
    width: 110px;
    text-align: left;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
  }

  .TopAdd {
    margin: 50px 0px 10px 0px;
    display: flex;
    justify-content: space-between;
  }

  .heig {
    height: 20px
  }
</style>
